package javaforce;

/**
 *
 * @author pquiring
 *
 * Created : Oct 8, 2013
 */

import java.security.*;
import java.security.spec.*;
import java.security.cert.*;
import java.io.*;
import java.util.*;

public class KeyMgmt {
  private KeyStore ks;

  /** Open an existing keystore (Note: use null for InputStream to create a blank keystore) */
  public boolean open(InputStream is, char[] pwd) {
    try {
      ks = KeyStore.getInstance("JKS", "SUN");
      ks.load(is, pwd);
      return true;
    } catch (Exception e) {
      JFLog.log(e);
      return false;
    }
  }

  public boolean save(OutputStream os, char[] pwd) {
    try {
      ks.store(os, pwd);
      return true;
    } catch (Exception e) {
      JFLog.log(e);
      return false;
    }
  }

  public boolean loadKEYandCRT(String alias, InputStream keyStream, InputStream certStream, char[] pwd) {
    try {
      // loading Key
      KeyFactory kf = KeyFactory.getInstance("RSA");
      byte key[] = JF.readAll(keyStream);
      PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key);
      PrivateKey ff = kf.generatePrivate (keysp);

      // loading CertificateChain
      CertificateFactory cf = CertificateFactory.getInstance("X.509");

      Collection c = cf.generateCertificates(certStream) ;
      java.security.cert.Certificate[] certs;

      certs = (java.security.cert.Certificate[])c.toArray();

      // set key / cert pair
      ks.setKeyEntry(alias, ff, pwd, certs);
      return true;
    } catch (Exception e) {
      JFLog.log(e);
      return false;
    }
  }

  public boolean loadCRT(String alias, InputStream certStream) {
    try {
      // loading CertificateChain
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      java.security.cert.Certificate crt = cf.generateCertificate(certStream);

      // set one cert
      ks.setCertificateEntry(alias, crt);
      return true;
    } catch (Exception e) {
      JFLog.log(e);
      return false;
    }
  }

  public boolean hasCRT(InputStream certStream) {
    try {
      // loading CertificateChain
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      java.security.cert.Certificate crt = cf.generateCertificate(certStream);

      return ks.getCertificateAlias(crt) != null;
    } catch (Exception e) {
      JFLog.log(e);
      return false;
    }
  }
}
